using System;

namespace HalconDotNet
{
	internal class HDevParamGuard : IDisposable
	{
		protected IntPtr mThreadHandle;

		protected bool mGlobal;

		protected int mReferenceCount;

		public HDevParamGuard(IntPtr threadHandle, bool global)
		{
			mThreadHandle = threadHandle;
			mGlobal = global;
			mReferenceCount = 0;
			if (mGlobal)
			{
				HDevThread.HCkHLib(HalconAPI.HXThreadLockGlobalVar(mThreadHandle));
				return;
			}
			HDevThread.HCkHLib(HalconAPI.HXThreadLockLocalVar(mThreadHandle, out IntPtr referenceCount));
			mReferenceCount = referenceCount.ToInt32();
		}

		public bool IsAvailable()
		{
			if (!mGlobal)
			{
				return mReferenceCount > 1;
			}
			return true;
		}

		public void Dispose()
		{
			if (mGlobal)
			{
				HDevThread.HCkHLib(HalconAPI.HXThreadUnlockGlobalVar(mThreadHandle));
			}
			else
			{
				HDevThread.HCkHLib(HalconAPI.HXThreadUnlockLocalVar(mThreadHandle));
			}
		}
	}
}
